package com.dongdongshop.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.dongdongshop.mapper.TbGoodsDescMapper;
import com.dongdongshop.mapper.TbGoodsMapper;
import com.dongdongshop.mapper.TbItemMapper;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.GoodsService;
import com.dongdongshop.vo.GoodsVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@DubboService
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private TbGoodsMapper tbGoodsMapper;
    @Autowired
    private TbGoodsDescMapper tbGoodsDescMapper;
    @Autowired
    private TbItemMapper tbItemMapper;

    @Transactional
    @Override
    public void addGoods(TbGoods tbGoods, TbGoodsDesc tbGoodsDesc, List<TbItem> tbItems) {
        tbGoodsMapper.insertSelective(tbGoods);
        tbGoodsDesc.setGoodsId(tbGoods.getId());
        tbGoodsDescMapper.insertSelective(tbGoodsDesc);

        tbItems.forEach(tbItem -> {
            tbItem.setCreateTime(new Date());
            tbItem.setUpdateTime(new Date());
            tbItem.setGoodsId(tbGoods.getId());
            tbItemMapper.insertSelective(tbItem);
        });
        //设置默认sku
        TbItemExample example = new TbItemExample();
        TbItemExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsIdEqualTo(tbGoods.getId());
        List<TbItem> tbItems1 = tbItemMapper.selectByExample(example);
        tbGoods.setDefaultItemId(tbItems1.get(0).getId());
        tbGoodsMapper.updateByPrimaryKeySelective(tbGoods);
    }

    @Override
    public List<GoodsVo> listGoods() {
        return tbGoodsMapper.listGoods();
    }

    @Override
    public void updateAuditStatus(List<Long> ids, String status) {
        TbGoodsExample example = new TbGoodsExample();
        TbGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(ids);

        TbGoods tbGoods = new TbGoods();
        tbGoods.setAuditStatus(status);

        tbGoodsMapper.updateByExampleSelective(tbGoods,example);

    }

    @Override
    public TbGoods getGoodsById(Long goodsId) {
        return tbGoodsMapper.selectByPrimaryKey(goodsId);
    }
}
